//
//  EchoClient.m
//  EchoServer
//
//  Created by Arthur on 15/6/8.
//  Copyright (c) 2015年 Arthur. All rights reserved.
//

#import "EchoClient.h"
#import <CoreFoundation/CoreFoundation.h>
#import <sys/socket.h>
#import <arpa/inet.h>
#import <netinet/in.h>

@implementation EchoClient

- (id)initWithAddr:(NSString *)addr andPort:(int)port{
    self = [super init];
    if(self){
        self.socketFd = CFSocketCreate(CFAllocatorGetDefault(), AF_INET,SOCK_STREAM,IPPROTO_TCP,0,NULL,NULL);
        if(self.socketFd == NULL){
            self.errorCode = SOCKETERROR;
        }
        else{
            struct sockaddr_in serverAddr;
            memset(&serverAddr, 0, sizeof(serverAddr));
            serverAddr.sin_len = sizeof(serverAddr);
            serverAddr.sin_family = AF_INET;
            serverAddr.sin_port = htons(port);
            inet_pton(AF_INET, [addr cStringUsingEncoding:NSUTF8StringEncoding], &serverAddr.sin_addr);
            CFDataRef connectAddr = CFDataCreate(NULL, (unsigned char *)&serverAddr, sizeof(serverAddr));
            if(connectAddr == NULL){
                self.errorCode = CONNECTERROR;
            }
            else{
                if((CFSocketConnectToAddress(self.socketFd, connectAddr, 30)) != kCFSocketSuccess ){
                    self.errorCode = CONNECTERROR;
                }
               
            }
        }
    
    }
    
    return self;
}

- (ssize_t)writeToSocket:(CFSocketRef)socketFdNum withStr:(NSString *)str{
    ssize_t n;
    
    n = [self sendToSocket:socketFdNum withData:[str dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    return n;
}

- (ssize_t)sendToSocket:(CFSocketRef)lsoFd withData:(NSData *)data{
    ssize_t n;
    
    NSLog(@"sending data");
    
    const UInt8* buffer = (const UInt8*)[data bytes];
    
    CFSocketNativeHandle sock = CFSocketGetNative(lsoFd);
    
    if((n = send(sock,buffer,[data length],0)) <= 0){
        self.errorCode = WRITEERROR;
    }
    else{
        self.errorCode = NOERROR;
    }
    
    SAFE_CF_RELEASE(lsoFd);
    
    return n;
}

@end
